//插件加载
import config from '../../mods/Config.js';
import WebSocket from "ws";
import chalk from 'chalk';
import { ping, Permissions, Write_data, Read_data, Read_list } from '../all/all.js'
import Show from '../../mods/show.js';
import puppeteer from '../../../../lib/puppeteer/puppeteer.js';
let testWebSocket;
export class say extends plugin {
    constructor() {
        /**
         * ServerTap api网址
         * http://localhost:55590/swagger
         */
        super({
            name: 'say',
            dsc: '获取消息模块',
            event: 'message',
            priority: 600,
            rule: [
                {
                    reg: '^(#|/)开启消息获取$',
                    fnc: 'open_say',
                },
                {
                    reg: '^(#|/)关闭消息获取$',
                    fnc: 'close_say',
                },
                {
                    reg: '^(#|/)获取消息.*',
                    fnc: 'show_log',
                }
            ],
        });
    }
    async show_log(e) {
        let thing = e.msg.replace('#', '');
        thing = thing.replace('/', '');
        thing = thing.replace('获取消息', '');
        const code = thing.split('*');
        let num = code[0]
        if (num == undefined || num == 0 || num < 0) {
            num = 0
        } else {
            num -= 1
        }
        let img = await get_log_img(e, num);
        e.reply(img);
        return;
    }
    async open_say(e) {
        //做个防呆
        if (testWebSocket != undefined) {
            e.reply("已经开启消息获取了，不能重复开哦~");
            return;
        }
        let qq = e.user_id
        let yanzheng = await Permissions(qq, 1, e)
        if (!yanzheng) return;
        let ok = await ping();
        if (!ok) {
            e.reply("服务器未开启！");
            return;
        }
        test(e, 0);
        return;
    }
    async close_say(e) {
        //做个防呆
        if (testWebSocket == undefined) {
            e.reply("请先开启消息获取！");
            return;
        }
        let qq = e.user_id
        let yanzheng = await Permissions(qq, 1, e)
        if (!yanzheng) return;
        let ok = await ping();
        if (!ok) {
            e.reply("服务器未开启！");
            return;
        }
        testWebSocket.close()
        testWebSocket = undefined
        e.reply(`消息获取已关闭！`)
        return;
    }
}
async function test(e, i) {
    let ok = await ping();
    if (!ok) {
        logger.info(chalk.red('服务器已关闭！'));
        testWebSocket = undefined
        return;
    }
    let mcConfigData = config.getConfig('mc');
    const ip = `${mcConfigData.ip}:${mcConfigData.port}`
    if (!testWebSocket) {
        testWebSocket = new WebSocket(`ws://${ip}/v1/ws/console`);
        testWebSocket.onopen = function (event) {
            if (i == 0) {
                testWebSocket.send("say 频道机器人连接成功！");
            } else {
                logger.info(chalk.green('频道机器人重连成功！'));
            }
        };
    }
    else {
        if (i == 0) {
            testWebSocket.send("say 频道机器人连接成功！");
        } else {
            logger.info(chalk.green('频道机器人重连成功！'));
        }
    }
    testWebSocket.onmessage = function (event) {
        const say = event.data;
        const data = JSON.parse(say);
        //过滤消息
        if (data.loggerName == 'net.minecraft.server.MinecraftServer') {
            message(data)
        }
    }
    testWebSocket.onclose = function (e) {
        if (e.code != 1005) {
            logger.info(chalk.red('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean));
            logger.info(chalk.yellow('正在尝试重连...'));
            chonglian();
        }
    }
    function chonglian() {
        testWebSocket = undefined
        test(e, 1)
    }
    if (i == 0) {
        e.reply(`消息获取已开启！`);
    }
    return;
}
async function message(data) {
    data.message = data.message.replace('[', '');
    data.message = data.message.replace(']', '');
    data.message = data.message.replace('>', '');
    data.message = data.message.replace('<', '');
    const code = data.message.split(' ');
    let wenan = ``;
    const new_data = await Read_list()
    let num = [];
    let name = [];
    // console.log(code);//检查专用
    //循环全部翻译json
    xunhuan:
    for (let i in new_data) {
        //分割
        const Translation = new_data[i].reception.split(' ');
        //看看是不是玩家发言
        if (code[0] == "Not" && code[1] == "Secure" && code[2] == "[Server]") {
            code.splice(0, 3);
            let say = ``
            for (let b in code) {
                say += code[b];
            }
            wenan = `控制台发言:${say}`;
            break xunhuan
        } else if (code[0] == "Not" && code[1] == "Secure" && code[2] == '[Rcon]') {
            code.splice(0, 3);
            let say = ``
            for (let b in code) {
                say += code[b];
            }
            wenan = `频道发言:${say}`;
            break xunhuan
        } else if (code[0] == "Not" && code[1] == "Secure") {
            code.splice(0, 2);
            let say = ``
            for (let b in code) {
                say += code[b];
            }
            wenan = `游戏内玩家发言:${say}`;
            break xunhuan
        }
        //比较长度是否正确
        if (Translation.length != code.length) continue;
        //开始循环比较
        for (let o in Translation) {
            //#号跳过并记录
            if (Translation[o] == "#") {
                //记录数组
                num.push(o);
                name.push(code[o]);
                continue;
            }
            //不对就不是这个
            if (Translation[o] != code[o]) {
                //记得清理一下数组
                num = [];
                name = [];
                continue xunhuan;
            }
        }
        //正确了
        let Translation_wenan = new_data[i].Send.split(' ');
        for (let x in num) {
            Translation_wenan[num[x]] = name[x];
        }
        if (new_data[i].log == 1) {
            let say = ``
            for (let c in Translation_wenan) {
                say += Translation_wenan[c];
            }
            //该log不记录
            console.log(say);
            return;
        }
        for (let b in Translation_wenan) {
            if(Translation_wenan[b] == `#`) continue
            wenan += Translation_wenan[b];
        }
        break;
    }
    //没比对出来就直接录入
    if (wenan == ``) wenan = data.message;
    console.log(wenan);
    const date = new Date();  // 参数需要毫秒数，所以这里将秒数乘于 1000
    const Y = date.getFullYear();
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    const D = date.getDate();
    const h = date.getHours();
    const m = date.getMinutes();
    const today = `${Y}${M}${D}`;
    wenan += `(${h}:${m})`;
    try {
        let data = await Read_data(today);
        data.push(wenan);
        await Write_data(today, data);
    }
    catch {
        const data = [wenan];
        await Write_data(today, data);
    }
    return;
}
export async function get_log_img(e, num) {
    const date = new Date();
    const Y = date.getFullYear();
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    const D = date.getDate();
    const today = `${Y}${M}${D}`;
    let data;
    try {
        data = await Read_data(today);
    }
    catch {
        e.reply(`该日暂无消息`);
        return;
    }
    const num1 = num * 18;
    const num2 = num1 + 18;
    const nummix = Math.ceil(data.length / 18);
    const numnow = num += 1;
    const data2 = data.slice(num1, num2);
    const new_data = {
        log: data2,
        numnow,
        nummix
    }
    if (numnow > nummix) {
        e.reply(`貌似没有这页呢！`)
        return
    }
    const data1 = await new Show(e).get_log(new_data);
    return await puppeteer.screenshot('log', {
        ...data1,
    });
}
